﻿using System.Collections.Generic;

namespace Common.Files
{
    public class ConfigFileHelper
    {
        private static Dictionary<string, string> dic = new Dictionary<string, string>();
        private static object lockObj = new object();

        public static string GetConfigSetting(string key)
        {
            if (dic.ContainsKey(key) == false)
            {
                lock (lockObj)
                {
                    if (dic.ContainsKey(key) == false)
                    {
                        dic.Add(key, System.Configuration.ConfigurationManager.AppSettings[key]);
                    }
                }
            }
            return dic[key];
        }
        /// <summary>
        /// 文件后缀(文件类型)
        /// </summary>
        private static string FileSuffix
        {
            get
            {
                string ConfigFileSuffix = GetConfigSetting("ConfigFileSuffix");
                return ConfigFileSuffix ?? "json";
            }
        }
        /// <summary>
        /// 根据文件地址一次性获取文件全部内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="isHeadSuffix">是否加文件后缀（默认不加后缀，动态配置文件）</param>
        /// <returns></returns>
        public static string GetFileContent(string filePath, bool isHeadSuffix = false)
        {
            if (!isHeadSuffix)
                filePath += "." + FileSuffix.TrimStart('.');
            string str = System.IO.File.ReadAllText(filePath);
            return str;
        }
        /// <summary>
        /// 根据文件地址一次性获取文件全部内容并转为指定对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <param name="isHeadSuffix">是否加文件后缀（默认不加后缀，由配置文件动态配置）</param>
        /// <returns></returns>
        public static T GetFileContent<T>(string filePath, bool isHeadSuffix = false)
        {
            string str = GetFileContent(filePath, isHeadSuffix);
            //获取文件后缀
            string _fileSuffix = "";
            if (!isHeadSuffix)
            {
                _fileSuffix = FileSuffix;
            }
            else
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
                _fileSuffix = fi.Extension;
            }
            T lds = default(T);
            if (_fileSuffix.ToLower() == "json")
                lds = Common.Serialize.JsonHelper.ToObject<T>(str);
            else
                lds = Common.Serialize.XMLHelper.ToObject<T>(str);
            return lds;
        }
    }
}
